package com.lyy.common.utils;

import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @author 俞伟
 * @version 1.0
 * @date 2020/10/26
 * @description com.lyy.common.utils
 */
@Slf4j
public class FileUtils {
    /**
     * 将BufferedImage转换为InputStream
     *
     * @param image
     * @return
     */
    public static InputStream bufferedImageToInputStream(BufferedImage image) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "png", os);
            return new ByteArrayInputStream(os.toByteArray());
        } catch (IOException e) {
            log.error("BufferedImage转换为InputStream出现异常::{}", e.getMessage());
        }
        return null;
    }

    /**
     * 字符流写
     *
     * @param path
     * @param context
     * @return
     */
    public static boolean writer(String path, String context) {
        FileWriter fileWriter = null;
        BufferedWriter bufferedWriter = null;
        try {
            fileWriter = new FileWriter(path);
            bufferedWriter = new BufferedWriter(fileWriter);
            String s = new String(context.getBytes(), StandardCharsets.UTF_8);
            bufferedWriter.write(s);
            bufferedWriter.flush();
        } catch (IOException e) {
            return false;
        } finally {
            try {
                if (fileWriter != null) {
                    fileWriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (bufferedWriter != null) {
                    bufferedWriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }

    /**
     * 读取文件
     *
     * @param path
     */
    public static byte[] myRead(String path) {
        File file = new File(path);    //1、建立连接
        InputStream is = null;
        try {
            is = new FileInputStream(file);    //2、选择流(此处为输入流)
//            //和上一句功能一样，BufferedInputStream是增强流，加上之后能提高输入效率，建议！
//            is = new BufferedInputStream(new FileInputStream(file));
            int len = 0;
            byte[] car = new byte[(int) file.length()];
            if ((len = is.read(car)) != -1) {    //3、操作：以每次car大小读取
                return car;
            }
//            while ((len = is.read(car)) != -1) {    //3、操作：以每次car大小读取
//                String ss = new String(car, 0, len);    // 将byte类型的数组转化成字符串，方便下面输出
//                System.out.println(ss);
//            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {    //若is还存在就需要释放，否则不需要释放
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 二、写出文件
     * 1、建立联系   File对象  目的地
     * 2、选择流     文件输出流  OutputStream FileOutputStream
     * 3、操作  :  write() +flush
     * 4、释放资源 :关闭
     *
     * @param path
     */
    public static void myWrite(String path, byte[] context) {
        File file = new File(path);    //1、建立连接
        OutputStream os = null;
        try {
            //2、选择输出流,以追加形式(在原有内容上追加) 写出文件 必须为true 否则为覆盖
            os = new FileOutputStream(file, true);
//            //和上一句功能一样，BufferedInputStream是增强流，加上之后能提高输出效率，建议
//            os = new BufferedOutputStream(new FileOutputStream(file,true));
            os.write(context, 0, context.length);    //3、写入文件
            os.flush();    //将存储在管道中的数据强制刷新出去
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            log.error("文件没有找到！");
        } catch (IOException e) {
            e.printStackTrace();
            log.error("写入文件失败！");
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    log.error("关闭输出流失败！");
                }
            }
        }
    }

    /**
     * 将InputStream写入本地文件
     *
     * @param destination 写入本地目录
     * @param input       输入流
     * @throws IOException
     */
    public static void writeToLocal(String destination, InputStream input) {
        try {
            int index;
            byte[] bytes = new byte[1024];
            FileOutputStream downloadFile = new FileOutputStream(destination);
            while ((index = input.read(bytes)) != -1) {
                downloadFile.write(bytes, 0, index);
                downloadFile.flush();
            }
            downloadFile.close();
            input.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 将InputStream写入本地文件
     *
     * @param destination 写入本地目录
     * @param input       输入流
     * @param fileName    文件名称
     * @throws IOException
     */
    public static boolean writeFileToLocal(String destination, String fileName, InputStream input) {
        try {
            int index;
            byte[] bytes = new byte[1024];
            File file = new File(Constants.basePath + destination);
            if (!file.exists()) {
                file.mkdirs();
            }
            FileOutputStream downloadFile = new FileOutputStream(Constants.basePath + destination + fileName);
            while ((index = input.read(bytes)) != -1) {
                downloadFile.write(bytes, 0, index);
                downloadFile.flush();
            }
            downloadFile.close();
            input.close();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

}
